class Compiler {
  constructor(vm) {
    // store element for future usage
    this.el = vm.$el;
    this.vm = vm;
  }
  compile(el) {
    // compile 模板
    let childNodes = el.childNodes;
    Array.from(childNodes).forEach((node) => {
      if (this.isTextNode(node)) {
        this.compileText(node);
      } else if (this.isElementNode(node)) {
        this.compileElement(node);
      }

      // has child node?
      if (node.childNodes && node.childNodes.length) {
        this.compile(node);
      }
    });
  }
  compileElement(node) {
    // element node
    // console.log(node.attributes);
    // 遍历所有的属性节点
    Array.from(node.attributes).forEach((attr) => {
      // 判断是否是指令！
      let attrName = attr.name;
      if (this.isDirective(attrName)) {
        // v-text ==> text
        attrName = attrName.substr(2);
        // @ ==> v-on
        if (attrName==="@") {
          attrName = "on"
        }
        let key = attr.value;
      }
    });
  },
  update(node,key,attrName) {
    let updateFn = this[attrName + 'Updater']
    // node是dom元素，key是dom元素要显示的值的key，通过key获得需要显示的value
    updateFn && updateFn(node,this.vm[key])
  },
  // v-text
  textUpdater(node,value) {
    node.textContent = value
  },
  // v-html 将字符串当成html标签解析出来!
  htmlUpdater(node,value) {
    node.innerHTML = value
  },
  // v-on @ 选中当前的dom元素然后为其添加相应的dom事件,传入的参数是一个函数名!
  onUpdater(node,funcName,value) {
    // 把value的值和对应的function绑定
    node.addEventListener(funcName, value)
  },
  // v-model
  modelUpdater(node,value) {
    node.value = value
  },
  compileText(node) {
    // text node
    // api for get value in the text nodeValue || textContent
    // re
    // {{ msg }} 前后可能有空格也可能没有空格
    let reg = /\{\{(.+)\}\}/;
    let value = node.textContent;
    if (reg.test(value)) {
      let key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);
    }
  }
  isDirective(attrName) {
    // is directive ?
    return attrName.startsWith("v-");
  }
  isTextNode(node) {
    // is text node ?
    return node.nodeType === 3;
  }
  isElementNode(node) {
    return node.nodeType === 1;
  }
}
